<template>
  <div class="agent" v-loading="loading">
    <div v-show = "isShowChild">
      <div class="top">
        <p class="topTip">温馨提示：在线状态总时长、忙碌状态总时长、自定义状态总时长及各个自定义状态时长统计只有以座席为维度查询时展示结果</p>
        <div class="search">
          <div class="contition">
            <div class="wrap_time">
              <date-time @changeDateS="childTimeChange" type="other_half_hour" @changeType="changeType" :query="query" @isFold="isShowFold" :isTimePeriod = "true"></date-time>
              <el-button type="primary" class="primary_btn fr find" @click.stop='search'>{{$t('public.search2')}}</el-button>
              <div class="clear"></div></div>
            <div class="wrap_drop">
              <unfold :isShow="isFold" :title="[]">
                <template slot="unfoldSlot">
                  <div class="accs">
                    <span class="access">{{$t('report.imAccessId')}}：</span>
                    <el-select size="mini" v-model.trim="selectedAccessIdList" multiple filterable :placeholder="$t('report.searchByName')">
                      <el-option
                        v-for="item in accessIdOptions"
                        :label="item.label"
                        :value="item.value"
                        :key="item.value">
                      </el-option>
                    </el-select>
                  </div>
                  <div class="agent_search">
                    <div class="skill">
                      <el-radio-group v-model="radio1"
                                    size = "mini"
                                    @change = "changeAgentBig">
                        <el-radio :label="1">{{$t('report.lookAgentWork')}}</el-radio>
                        <el-radio :label="0">{{$t('report.lookSkillWork')}}</el-radio>
                        <span class="tip">
                          <el-tooltip
                            transition="fade-leave"
                            effect="dark"
                            :content="$t('report.queueChangeAgentTip')"
                            placement="bottom">
                            <i class="icon iconfont icon-tixingweizhi"></i>
                          </el-tooltip>
                        </span>
                      </el-radio-group></div>
                    <div class="wrap_conti" v-show="radio1">
                      <span class="chan_ag">{{$t('report.chooseAgent')}}:</span>
                      <el-radio-group v-model="radio3"
                                    size = "mini"
                                    @change = "changeAgent">
                        <div>
                          <el-radio :label="1">{{$t('public.checkAll')}}</el-radio></div>
                        <div :class="[{wrap_agents: wrapAgents}, 'skill']">
                          <el-radio :label="2">{{$t('report.accordAgentChoose')}}</el-radio>
                          <!-- <el-select v-model="selectedAgentList"
                                    multiple
                                    filterable
                                    :disabled = "radio3 !== 2"
                                    size="mini"
                                    @change="agentsChange"
                                    :placeholder="$t('report.pleChoseAgent')">
                              <el-option
                                v-for="item in agentOptions"
                                :label="item.label"
                                :value="item.value"
                                :key="item.value">
                              </el-option></el-select> -->
                          <m7Select class="el-select" :disabled = "radio3 !== 2" filterable multiple :options="selectAgents" v-model="selectedAgentList"></m7Select>
                          <el-checkbox :disabled = "radio3 !== 2"
                                      v-model.trim="query.includeSubordinate">
                            {{$t('public.includeSubordinate')}}</el-checkbox></div>
                        <div class="skill">
                          <el-radio :label="3">{{$t('report.chooseSkillAgent')}}</el-radio>
                          <el-select size="mini"
                                    v-model.trim="currentQueue"
                                    :placeholder="$t('report.queueNaSea')"
                                    multiple
                                    :disabled = "radio3 !== 3"
                                    filterable
                                    @change = "change">
                            <el-option v-for="item in mailQueues"
                                      :label="item.DisplayName"
                                      :value="item._id"
                                      :key="item._id"></el-option>
                          </el-select>
                          <el-checkbox :disabled = "radio3 !== 3"
                                        v-model.trim="isShowAgent">
                              {{$t('report.isShowSkillAgent')}}</el-checkbox></div>
                        <div class="skill dept" v-show="!flag">
                          <el-radio :label="4">{{$t('report.accordDeptChoose')}} </el-radio>
                          <el-select size="mini"
                                    v-model.trim="currentdept"
                                    :placeholder="$t('report.deptNaSea')"
                                    multiple
                                    :disabled = "radio3 !== 4"
                                    filterable
                                    @change = "changeDept">
                            <el-option v-for="item in depts"
                                      :label="item.name"
                                      :value="item.treePath"
                                      :key="item._id"></el-option>
                          </el-select>
                          <el-checkbox :disabled = "radio3 !== 4"
                                      v-model.trim="isShowDeptAgent"
                                      @change="changeShowDept">
                              {{$t('report.isShowDeptAgent')}}</el-checkbox></div>
                      </el-radio-group>
                    </div>
                    <div class="wrap_conti" v-show="!radio1">
                      <div class="skill">
                        <span class="ski">{{$t('report.chooseSkill')}}:</span>
                        <el-select size="mini"
                                      v-model.trim="currentQueueS"
                                      :placeholder="$t('report.queueNaSea')"
                                      filterable
                                      @change = "changeSkill">
                          <el-option v-for="item in mailQueues"
                                    :label="item.DisplayName"
                                    :value="item.Exten"
                                    :key="item._id"></el-option>
                        </el-select>
                      </div>
                    </div>
                  </div>
                </template>
              </unfold>
            </div>
          </div>
        </div>
        <affix :label="title"></affix>
      </div>
      <div :id="id">
        <el-row class="ichars">
          <highcharts :options="highchartsOptions"></highcharts>
          <div class="notes">
            <span class="light">{{$t('report.hicharsNotes')}}: <span></span>{{$t('report.hicharsLight')}}</span>
            <span class="dark"><span></span>{{$t('report.hicharsDark')}}</span>
          </div>
        </el-row>
        <div class="tab agent_table deal_margin">
          <div class="export">
            <el-button class="primary_btn fr formal"  v-if="configFormula" @click="$refs.formulaEditorDialog.open()">{{$t('report.formalTitle')}}</el-button>
            <el-button class="primary_btn fr set_header" v-on:click.stop="isHeaderConfigShow=!isHeaderConfigShow" v-if="!configHeaderBool">{{$t('report.setHeaderConfig')}}</el-button>

            <!-- <el-button class="primary_btn fr report_excel_btn"
              v-if="$store.getters.exportFromEnd && !flag"
              @click.stop="exportXls"
            >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

            <el-button class="primary_btn fr report_excel_btn"
              v-if="!flag"
              @click.stop="exportXlsx"
            >{{$t('report.exportXls')}}</el-button>

            <el-button class="primary_btn fr pdf" @click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
            <!-- <el-button class="primary_btn fr pdf" v-show="isShowDetailExport" v-on:click.stop="exportXls(true)">{{$t('report.imExportDetailXls')}}
            </el-button> -->
            <el-tooltip class="item" :content="$t('report.detailText')" effect="dark" placement="bottom">
              <el-button class="primary_btn fr pdf" v-show="isShowDetailExport && !flag" v-on:click.stop="exportXls(true)">{{$t('report.exportDetailXls')}}
                <span class="tip"><i class="iconfont icon-tixingweizhi"></i></span>
              </el-button>
            </el-tooltip>
          </div>
          <div class="deploy">
            <el-collapse accordion>
              <el-collapse-item>
                <template slot="title">
                  <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
                </template>
                <div>
                  1. {{$t('report.imQueueReplyNumAll')}} <br>
                  2. {{$t('report.imQueueAccessNum1')}} <br>
                  3. {{$t('report.responseTotalCount')}} <br>
                  4. {{$t('report.withdrawCount')}} <br>
                  5. {{$t('report.imSeatInviteNum')}} <br>
                  6. {{$t('report.imInviteAllNum')}} <br>
                  7. {{$t('report.inviteSessionRate')}} <br>
                  8. {{$t('report.imTurnToSession')}} <br>
                  9. {{$t('report.imturnOutSession')}} <br>
                  10. {{$t('report.finishConverNumber')}} <br>
                  11. {{$t('report.conSationFin')}}<br>
                  12. {{$t('report.averExchangeTime')}}<br>
                  13. {{$t('report.averResponseTime')}}<br>
                  14. {{$t('report.imFineSessionNum1')}}<br>
                  15. {{$t('report.imBadSessionNum1')}}<br>
                  16. {{$t('report.imKindSessionNum1')}}<br>
                  17. {{$t('report.imTurnCustomNum')}}<br>
                  18. {{$t('report.imEveryAskNum')}}<br>
                  19. {{$t('report.addVistorCount')}}<br>
                  20. {{$t('report.reponseIn40sCount')}}<br>
                  21. {{$t('report.reponseIn40sRate')}}<br>
                  22. {{$t('report.accessMessage')}}<br>
                  23. {{$t('report.finishMessage')}}<br>
                  24. {{$t('report.onlineStatusTotalLength')}}<br>
                  25. {{$t('report.busyStatusTotalLength')}}<br>
                  26. {{$t('report.customStatusTotalLength')}}<br>
                  27. {{$t('report.24hOneTimeResolutionRate')}}<br>
                  28. {{$t('report.48hOneTimeResolutionRate')}}<br>
                  29. {{ $t('report.sessionsQueueCount')}}<br/>
                  30. {{ $t('report.visitorMessagesNum')}}<br/>
                  31. {{ $t('report.pcLoginDuration')}}<br/>
                  32. {{ $t('report.appLoginDuration')}}<br/>
                  <p class="custom_alg">{{$t('report.ziDingYi')}}：</p>
                  <p v-for="(item, index) in formulas" :key="item.name">
                    {{index + 33}}.{{item.formulaInstr}}
                  </p>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
          <checkbox-table :isDrill="isDrill" :data="tableData" :sum="totalData" :config="[...headOptions.Config, ...formulasConfig]" @agentName = "intiCondition" @tellme = "reducteDate"> </checkbox-table>
        </div>
      </div>
      <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
        <span>{{$t('report.reportExportTipTitle')}}</span>
        <span slot="footer" class="dialog-footer">
          <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
          <el-button type="primary" class="primary_btn" @click="confirm">{{$t('public.confirm')}}</el-button>
        </span>
      </el-dialog>
      <header-option v-show="isHeaderConfigShow" :show="isHeaderConfigShow" :option="headOptionsShow" :type="id" v-on:close="close" :headCustom="formulasConfig"></header-option>
    </div>
    <QueryAgentWork v-show="!isShowChild" ref="myChild" @flag = "show" :customConfig="formulasConfig" :formulas="formulas"  :condition = "{childQuery, dateSource, agentName}"></QueryAgentWork>
    <!-- 自定义公式组件 -->
    <FormulaEditorDialog ref="formulaEditorDialog" :headOptionsConfig="headOptions.Config" @closeFormulaDialog="closeFormulaDialog" :reportType="id"/>
  </div>
</template>
<script>
  import affix from '../../../ui-modules/affix/Affix.vue'
  import unfold from '../../../ui-modules/unfold/index.vue'
  import dateTime from '../base/dateDrill.vue'
  import headerOption from '../base/headerOption.vue'
  import checkboxTable from '../base/checkboxTable.vue'
  import QueryAgentWork from './QueryAgentWork.vue'
  import { deepClone, getFormatTimeBySecond, optionTimeTypeCheck, getDateTime, isHasFunc  } from '@/utils/m7Utils.js'
  import { exportReportPdf, headOptionsToXlsxHeaders, checkTime, searchTime, colorConfigArr, mixData } from '@/utils/reportUtils.js'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  import FormulaEditorDialog from '../base/FormulaEditorDialog.vue'
  export default {
    name: 'im_report_agent',
    data () {
      return {
        configFormula: true, // 自定义公式的权限
        flag: this.$store.getters.isEcommerce ? true : false, // 是否是电商平台
        dateSource: {}, // 钻入需要的数据
        childQuery: {}, // 子组件查询条件
        agentName: '', // 点击查询座席的名称
        isDrill: true, // 是否为钻入座席组件
        isShowChild: true, // 是否显示子组件开关
        dateType: 'day', // 当前选择时间类型
        isSearch: false, // 查询时不触发监听自定义表头的变化
        formulas: [], // 公式数据
        wrapAgents: false, // 是防止座席数据量展示太大设置样式index -1
        isShowAgent: false, // 是否展示技能组下的座席
        isShowDeptAgent: false, // 是否展示部门下的座席
        accessIdOptions: [], // 接入号数据
        selectedAccessIdList: [], // 接入号绑定值
        isFold: false, // 是否展示搜索条件
        currentQueueS: '', // 技能组号
        radio3: 1, // 各座席工作量下面选择切换绑定得值
        radio1: 1, // 各座席工作量和各技能组切换绑定值
        depts: [], // 部门渲染下拉数据
        noDealDate: [], // 渲染合计数据
        currentdept: [], // 选择部门绑定得id值集合
        currentQueue: [], // 各座席工作量下技能组绑定值
        mailQueues: [], // 技能组信息集合
        id: 'im_report_agent',
        title: this.$t('report.imReportAgent'),
        loading: false,
        query: {includeSubordinate: false},
        dialogVisible: false,
        selectedAgentList: [], // 座席id集合
        selectedAgentListClone: [], // 是否展示座席得复制版
        agentOptions: [], // 渲染座席数据
        serverData: [],
        headOptions: { Config: [], data: [] }, // 表头数据
        headOptionsShow: { Config: [], data: [] }, // 渲染配置表头得数据
        isHeaderConfigShow: false, // 展示配置表头弹窗开关
        highchartsDefaultOptions: { // charts渲染配置
          chart: { type: 'column', animation: false },
          colors: colorConfigArr,
          xAxis: {
            categories: [],
            title: {
              enabled: true,
              text: '',
              style: { fontWeight: 'normal' }
            }
          },
          yAxis: {
            gridLineColor: '#e6e6e6',
            allowDecimals: false,
            title: { text: '' },
            showEmpty: false
          },
          title: { text: this.$t('report.imReportAgent') },
          legend: { align: 'center', verticalAlign: 'top', y: 30 },
          tooltip: {
            pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}{point.valueSuffix}</b><br/>',
            shared: true
          },
          credits: { enabled: false },
          series: []
        }
      }
    },
    components: {
      FormulaEditorDialog,
      affix,
      unfold,
      dateTime,
      checkboxTable,
      headerOption,
      QueryAgentWork
    },
    watch: {
      // 监测自定义公式变化 更新数据
      formulas (cur, old) {
        if (this.isSearch) {
          return
        }
        if (!this.serverData || this.serverData.length === 0) {
          return
        }
        this.serverData = mixData(deepClone(this.serverData), this.formulas)
        this.noDealDate = mixData(deepClone(this.serverData), this.formulas)
      },
      // 是否展示技能组下的座席
      isShowAgent (cur) {
        if (cur) {
          this.selectedAgentList = this.selectedAgentListClone
          this.wrapAgents = false
        } else {
          this.selectedAgentList = []
        }
      }
    },
    computed: {
      // 判断是否为过滤座席 返回座席下拉数据
      selectAgents () {
        if (this.$store.getters.userHidden === 'yes') {
          return this.$store.getters.filterStopAgents && this.$store.getters.filterStopAgents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id, deptId: agent.deptId ? agent.deptId : '' }))
        }
        return  this.agentOptions
      },
      // 是否展示导出详细excel
      isShowDetailExport () {
        let type = ['week', 'month', 'other_half_hour']
        return type.includes(this.dateType)
      },
      // 是否展示配置表头
      configHeaderBool () {
        return this.$store.state.report.setConfigHeaderBool
      },
      tableData () {
        return this.getTableData(deepClone(this.serverData), this.headOptions)
      },
      totalData () {
        return this.getTotalData(deepClone(this.noDealDate), this.headOptions)
      },
      highchartsOptions () {
        let options = deepClone(this.highchartsDefaultOptions)
        if (!this.noDealDate || this.noDealDate.length === 0) {
          return options
        }
        let headerConfig = this.headOptions.Config || []
        let datas = this.noDealDate
        let categoriesArray = []
        let seriesArray = []

        headerConfig.forEach(item => {
          if (!item.show) {
            return
          }
          // fortyEightHoursRepeatRate(48h一次性解决率)   
          // twentyFourHoursRepeatRate(24h一次性解决率)  
          // 以上这两项，因为和图表中的Y轴的值无法对应，所以隐藏掉在图表中的渲染
          if (item.name === 'agentName' || item.name === 'fortyEightHoursRepeatRate' || item.name === 'twentyFourHoursRepeatRate') {
            return
          }
          let serie = { name: item.displayname, data: [], valueName: item.name }
          if (item.name === 'sessionAverageTimeLength' || item.name === 'averageFirstResponseTimeLength' || item.name === 'closeSessionTotalTime' || item.name === 'openSessionTotalTime' || item.name === 'customSessionTotalTime' ||item.name === 'pcOpenSessionTotalTime' ||item.name === 'appOpenSessionTotalTime'  || item.name.indexOf('sessionTotalTime') > -1) {
            serie.tooltip = { valueSuffix: 's' }
          } else if (item.name === 'sessionCompleteRate' || item.name === 'sessionRollOutRate' || item.name === 'inviteSessionRate' || item.name === 'weixinInstantRespRate' || item.name === 'weiboInstantRespRate' || item.name === 'sdkInstantRespRate' || item.name === 'webchatInstantRespRate' || item.name === 'responeInstantTimeRate') {
            serie.tooltip = { valueSuffix: '%' }
          }
          seriesArray.push(serie)
        })

        for (let i = 0; i < datas.length; i++) {
          categoriesArray.push(this.getAgentName(datas[i].agentId))
          for (let j = 0; j < seriesArray.length; j++) {
            seriesArray[j].data.push(datas[i][seriesArray[j].valueName])
          }
        }

        options.xAxis.categories = categoriesArray
        options.series = seriesArray
        return options
      },
      // 自定义表头
      formulasConfig () {
        return this.formulas.map((d, i) => {
          return {
            displayname: d.displayname,
            name: d.name,
            order: d.order,
            show: d.show,
            timeType: 'none',
            digits: d.digits,
            type: d.type
          }
        })
      }
    },
    methods: {
      // 钻入需要渲染的原始时间数据, 子组件传过来的方法
      childTimeChange (obj) {
        this.dateSource = obj
      },
      // 渲染钻入组件的查询条件
      intiCondition (id, name) {
        this.agentName = name
        let myQuery = deepClone(this.query)
        // 转化timeType查询条件
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        myQuery.reportType = 'call_report_agent'
        myQuery.AgentID = id
        this.childQuery = deepClone(myQuery)
        this.isShowChild = false
        this.$nextTick(() => {
          this.$refs.myChild.search1()
        })
      },
      // 子组件传上来的方法，判断是否显示子组件
      show () {
        this.isShowChild = true
      },
      // 子组件切换时间类型传上来得方法 触发计算属性
      changeType (type) {
        this.dateType = type
      },
      // 自定义公式弹窗关闭外抛事件
      closeFormulaDialog () {
        this.isSearch = false
        this.$store.dispatch('queryFetchFormula', {type: this.id}).then((resp) => {
          if (resp.success) {
            this.formulas = resp.data.Formulas
          }
        })
      },
      // 处理表格数据
      getTableData (serverData, headOptions, isExport) {
        if (!serverData || serverData.length === 0) {
          return []
        }
        let data = deepClone(serverData)
        data.forEach(item => {
          if (isExport) {
            var {displayName, exten} = this.getAgentDisplayNameAndExten(item.agentId)
            item.agentName = displayName
            item.agentExten = exten
          } else {
            item.agentName = this.getAgentName(item.agentId)
          }

          headOptions.Config.forEach((option, index) => {
            if (option.timeType && option.timeType === 'hhmmss') {
              item[option.name] = getFormatTimeBySecond(item[option.name])
            } else if (option.timeType && option.timeType === 'second') {
              item[option.name] = Math.round(item[option.name]) + 's'
            } else if (option.name.indexOf('Rate') > -1 && option.displayname.indexOf('率') > -1) {
              item[option.name] = `${item[option.name]}%`
            }
          })
        })
        return data
      },
      // 合计方法
      getTotalData (noDealDate, headOptions) {
        if (!noDealDate || noDealDate.length === 0) {
          return [{agentName: this.$t('report.total')}]
        }

        let headerConfig = headOptions.Config || []
        let datas = noDealDate
        // 定义一些合计用的上表头没有的字段
        let total = {
          agentName: this.$t('report.total'),
          sessionTotalTimeLength: 0,
          firstResponseTotalTimeLength: 0,
          responseTotalCount: 0
        }

        for (let i = 0; i < headerConfig.length; i++) {
          for (let j = 0; j < datas.length; j++) {
            if (!isNaN(datas[j][headerConfig[i].name])) {
              if ((headerConfig[i].name in total) === false) {
                total[headerConfig[i].name] = 0
              }
              total[headerConfig[i].name] += datas[j][headerConfig[i].name]
            }

            if (headerConfig[i].name === 'sessionAverageTimeLength') {
              total.sessionTotalTimeLength += datas[j]['sessionTotalTimeLength']
            } else if (headerConfig[i].name === 'averageFirstResponseTimeLength') {
              total.firstResponseTotalTimeLength += datas[j]['firstResponseTotalTimeLength']
            }
          }
        }
        // 48小时重复咨询次数
        let fortyEightHoursRepeatCount = 0
        // 24小时重复咨询次数
        let twentyFourHoursRepeatCount = 0
        datas.forEach(item => {
          if (item.fortyEightHoursRepeatCount) {
            fortyEightHoursRepeatCount += item.fortyEightHoursRepeatCount
          }
          if (item.twentyFourHoursRepeatCount) {
            twentyFourHoursRepeatCount += item.twentyFourHoursRepeatCount
          }
        })
        console.log(total)
        // 平均会话时长
        total.sessionAverageTimeLength = total.sessionCompleteCount + total.sessionRollOutCount > 0 ? Math.round(total.sessionTotalTimeLength / (total.sessionCompleteCount + total.sessionRollOutCount)) : 0
        // 平均首次响应时长
        total.averageFirstResponseTimeLength = total.responseTotalCount > 0 ? Math.round(total.firstResponseTotalTimeLength / total.responseTotalCount) : 0
        // 会话完成率
        total.sessionCompleteRate = total.sessionAccessCount + total.sessionRollInCount > 0 ? Math.round(((total.sessionCompleteCount + total.sessionRollOutCount) / (total.sessionAccessCount + total.sessionRollInCount + (total.inviteSessionCount || 0) + (total.activeClaimRobotSessionCount || 0) + (total.initiatingSessionCount || 0))) * 100) : 0
        // 会话转出率
        total.sessionRollOutRate = total.sessionAccessCount > 0 ? Math.round((total.sessionRollOutCount / total.sessionAccessCount) * 100) : 0
        // 主动邀请成功率
        total.inviteSessionRate = total.agentInviteCount > 0 ? Math.round((total.inviteSessionCount / total.agentInviteCount) * 100) : 0
        total.inviteSessionRate = total.inviteSessionRate > 100 ? 100 : total.inviteSessionRate
        // 40s及时响应率
        total.responeInstantTimeRate = total.responseTotalCount > 0 ? Math.round((total.instantRespTimeCount / total.responseTotalCount) * 100) : 0
        if (total.sessionAccessCount + total.sessionRollInCount - total.sessionRollOutCount) {
          // 48h一次性解决率
          total.fortyEightHoursRepeatRate = Math.round(((total.sessionAccessCount + total.sessionRollInCount - total.sessionRollOutCount - fortyEightHoursRepeatCount) / (total.sessionAccessCount + total.sessionRollInCount - total.sessionRollOutCount)) * 100)
          // 24h一次性解决率
          total.twentyFourHoursRepeatRate = Math.round(((total.sessionAccessCount + total.sessionRollInCount - total.sessionRollOutCount - twentyFourHoursRepeatCount) / (total.sessionAccessCount + total.sessionRollInCount - total.sessionRollOutCount)) * 100)
        } else {
          total.fortyEightHoursRepeatRate = 0
          total.twentyFourHoursRepeatRate = 0
        }
        total = mixData([total], this.formulas)[0]
        headOptions.Config.forEach((option, index) => {
          if (option.timeType && option.timeType === 'hhmmss') {
            total[option.name] = getFormatTimeBySecond(total[option.name])
          } else if (option.timeType && option.timeType === 'second') {
            total[option.name] = Math.round(total[option.name]) + 's'
          } else if (option.name.indexOf('Rate') > -1 && option.displayname.indexOf('率') > -1) {
            total[option.name] = `${total[option.name]}%`
          }
        })
        return [total]
      },
      // 座席组件改变得事件
      agentsChange () {
        if (this.wrapAgents) {
          this.wrapAgents = false
        }
      },
      // 是否展示部门下的座席
      changeShowDept (cur) {
        if (cur) {
          this.wrapAgents = false
          this.selectedAgentList = this.selectedAgentListClone
        } else {
          this.selectedAgentList = []
          this.wrapAgents = true
        }
      },
      // 展开收起查询条件方法
      isShowFold (bool) {
        this.isFold = bool
      },
      // 各座席工作量和技能组切换, 初始化一些数据
      changeAgentBig (num) {
        delete this.query.queryExten
        this.currentQueueS = ''
        this.selectedAgentList = []
        this.selectedAgentListClone = []
        this.currentQueue = []
        this.currentdept = []
        this.query.includeSubordinate = false
        this.isShowAgent = false
        this.isShowDeptAgent = false
        this.wrapAgents = false
      },
      // 切换按技能组查询下技能组触发方法 技能组号赋值给查询条件
      changeSkill (id) {
        this.query.queryExten = id
      },
      // 表格checkbox切换传过来得方法
      reducteDate (data) {
        let dealDate = []
        data.map(item => {
          this.serverData.map(col => {
            if (item.agentId === col.agentId) {
              dealDate.push(col)
            }
          })
        })
        this.noDealDate = dealDate
      },
      // 座席下拉切换执行得方法
      changeAgent () {
        this.selectedAgentList = []
        this.currentQueue = []
        this.currentdept = []
        this.selectedAgentListClone = []
        this.query.includeSubordinate = false
        this.isShowAgent = false
        this.isShowDeptAgent = false
        this.wrapAgents = false
      },
      // 部门切换执行得方法 筛选座席
      changeDept (deptTreePaths) {
        this.selectedAgentList = []
        this.selectedAgentListClone = []
        let deptIds = [] // 创建部门id数组集
        if (deptTreePaths.length !== 0) {
          for (let i = 0; i < deptTreePaths.length; i++) {
            if (deptTreePaths[i] === 'noDept') {
              deptIds.push('')
            } else {
              let deptIdArr = deptTreePaths[i].split('/')
              // deptIdArr长度为2为根部门
              if (deptIdArr.length === 2) {
                this.agentOptions.map(item => {
                  this.selectedAgentListClone.push(item.value)
                })
                if (this.isShowDeptAgent) {
                  this.selectedAgentList = this.selectedAgentListClone
                }
                break
              }
              let deptId = deptIdArr[deptIdArr.length - 2] // 当前部门id
              deptIds.push(deptId) // 像部门数组中添加当前部门id
              for (let j = 0; j < this.depts.length; j++) {
                let isDeptIdArr = this.depts[j].treePath.split(deptId + '/')[1] // 判断当前部门下面得部门是否存在
                if (isDeptIdArr) {
                  deptIds = deptIds.concat(isDeptIdArr.split('/').filter(item => item))
                }
              }
            }
          }
          deptIds = Array.from(new Set(deptIds)) // 部门id去重
          let cloneAgentsArr = []
          cloneAgentsArr = this.agentOptions.filter(item => { // 过滤座席信息得部门是否在部门数组里，是则返回
            return deptIds.includes(item.deptId)
          })
          cloneAgentsArr.map(item => {
            this.selectedAgentListClone.push(item.value)
          })
          if (this.isShowDeptAgent) {
            this.selectedAgentList = this.selectedAgentListClone
          }
        }
      },
      // 查看各座席下的技能组切换执行得 筛选座席方法
      change (peerIds) {
        this.selectedAgentListClone = []
        this.selectedAgentList = []
        this.includeSubordinate = false
        if (peerIds.length === 0) {
          return
        }
        let agentIds = []
        peerIds.map((id) => {
          this.mailQueues.map((item) => {
            if (item._id === id) {
              agentIds = agentIds.concat(item.AssignMembers)
            }
          })
        })
        agentIds.map((obj) => {
          if (obj) {
            this.selectedAgentListClone.push(obj.agentID)
          }
        })
        if (this.isShowAgent) {
          this.selectedAgentListClone = Array.from(new Set(this.selectedAgentListClone))
          this.selectedAgentList = this.selectedAgentListClone
        } else {
          this.selectedAgentListClone = Array.from(new Set(this.selectedAgentListClone))
        }
      },
      // 通过座席id返回座席姓名和工号string
      getAgentName (id) {
        let agent = this.$store.getters.agents[id]
        let getAgent = agent ? agent.displayName + '(' + agent.exten + ')' : ''
        return getAgent
      },
      // 通过座席id返回座席姓名和工号obj
      getAgentDisplayNameAndExten (id) {
        let agent = this.$store.getters.agents[id]
        return {
          displayName: agent ? agent.displayName : '',
          exten: agent ? agent.exten : ''
        }
      },
      // 导出详情为自定义进行得判断
      thanThirty (query) {
        let normalStartTime = query.normalStartTime
        let normalEndTime = query.normalEndTime
        let endTIme = normalEndTime.getTime()
        let startTime = normalStartTime.getTime()
        let diff = (endTIme - startTime) / (1000 * 60 * 60 * 24)
        // 大于三十天更改自定义得开始时间
        if (diff > 31) {
          let time = new Date(endTIme - 1000 * 60 * 60 * 24 * 31)
          let newStartTime = getDateTime(time, 'date')
          let lastTime = query.EndTime.split(' ')[1]
          query.StartTime = `${newStartTime} ${lastTime}`
        }
      },
      // 查询条件
      getSearchQueryData (page, limit) {
        let data = {
          reportType: this.id,
          account: this.$store.state.session.user.account,
          query: { reportType: this.id },
          user: {
            type: this.$store.state.session.user.type,
            moduleUsers: this.$store.state.session.user.moduleUsers
          }
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other_half_hour') {
          // 校验类型与时间
          let message = checkTime(query.StartTime, query.EndTime, false, false)
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        query.selectedAgentList = this.selectedAgentList.join(',')
        if (this.selectedAgentListClone.length > 0) {
          query.selectedAgentList = this.selectedAgentListClone.join(',')
        }
        if (this.selectedAccessIdList.length > 0) {
          query.selectedAccessIdList = this.selectedAccessIdList.join(',')
        }
        // 选择部门或技能组 但其下面无座席 故传显示无座席得值
        if ((this.currentQueue.length !== 0 || this.currentdept.length !== 0) && this.selectedAgentListClone.length === 0) {
          query.selectedAgentList = '000000'
        }
        data.query = Object.assign({}, data.query, query)

        return data
      },
      search () {
        var queryData = this.getSearchQueryData()

        if (!queryData) {
          return
        }

        var query = queryData.query
        this.loading = true
        this.$store.dispatch('queryImAgentReport', queryData).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          if (!res.success) {
            this.loading = false
            return
          }
          this.isSearch = true
          this.$store.dispatch('queryFetchFormula', {type: this.id}).then((resp) => {
            if (resp.success) {
              this.formulas = resp.data.Formulas
              // 表头
              if (res.tableHeader) {
                let tableHeaderArr = res.tableHeader.Config
                tableHeaderArr.forEach((item, index) => {
                  if (item.name === 'instantRespTimeCount' || item.name === 'responeInstantTimeRate') {
                    item.displayname = item.respTime + item.displayname
                  }
                })
              }
              this.headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || this.headOptions)
              if (res.tableHeader) {
                let tableDataHeader = res.tableHeader.Config.filter(item => {
                  return !item.isCustomConfig
                })
                res.tableHeader.Config = tableDataHeader
                this.headOptionsShow = optionTimeTypeCheck(deepClone(res.tableHeader))
              } else {
                this.headOptionsShow = optionTimeTypeCheck(this.headOptionsShow)
              }
              this.serverData = deepClone(mixData(res.data, this.formulas)) || deepClone(this.serverData)
              this.noDealDate = deepClone(mixData(res.data, this.formulas))
              this.loading = false
            }
          })
          //  图表标题 加入 定时段的 时间
          let highchartsTitle = ''
          if (query.timePeriod) {
            let timePeriodStartStr = query.timePeriodStart || '00:00'
            let timePeriodEndStr = query.timePeriodEnd || '23:59'
            highchartsTitle = '(' + timePeriodStartStr + '~' + timePeriodEndStr + ')'
          }
          this.highchartsDefaultOptions.title.text = this.$t('report.imReportAgent') + highchartsTitle
        })
      },
      exportXlsx (page) {
        var queryData = this.getSearchQueryData()

        if (!queryData) {
          return
        }

        this.loading = true
        this.$store.dispatch('queryImAgentReport', queryData).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          if (!res.success) {
            this.loading = false
            return
          }
          this.loading = false
          // 表头
          var headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || [])
          var serverData = mixData(deepClone(res.data), this.formulas) || []

          var ConfigsTemp = []
          headOptions.Config && headOptions.Config.forEach(config => {
            if (config.name === 'instantRespTimeCount') {
              config.displayname = config.respTime ? config.respTime + '及时响应数' : '40s及时响应数'
            } else if (config.name === 'responeInstantTimeRate') {
              config.displayname = config.respTime ? config.respTime + '及时响应率' : '40s及时响应率'
            }
            if (config.name !== 'everyCustomStatusTime') {
              ConfigsTemp.push(config)
            }
            if (config.name === 'agentName') {
              ConfigsTemp.push({
                show: config.show,
                displayname: '工号',
                name: 'agentExten'
              })
            }
          })
          headOptions.Config = ConfigsTemp

          var tableData = this.getTableData(serverData, headOptions, true)
          var headers = headOptionsToXlsxHeaders([...headOptions.Config, ...this.formulasConfig])

          if (tableData && tableData.length) {
            var sum = this.getTotalData(serverData, headOptions)
            tableData = tableData.concat(sum)
          }

          var dh = XlsxUtil.getDownloadHelper(headers, tableData)
          var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
          dh.download(this.$t('report.imReportAgent') + timeStamp)
        })
      },
      exportXls (bool) {
        let data = {
          Method: 'exportImAgent',
          Query: { reportType: this.id, user: this.$store.state.session.user._id }
        }
        // 导出详细excel更改method
        if (bool === true) {
          data.Method = 'exportImAgentDetail'
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other_half_hour') {
          let message = checkTime(query.StartTime, query.EndTime, true, false) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        // 是否为自定义时间导出并且点击详细导出
        if (query.timeType === 'other_half_hour' && bool === true && this.dateType !== 'week') {
          this.thanThirty(query)
        }
        query.selectedAgentList = this.selectedAgentList.join(',')
        if (this.selectedAgentListClone.length > 0) {
          query.selectedAgentList = this.selectedAgentListClone.join(',')
        }
        if (this.selectedAccessIdList.length > 0) {
          query.selectedAccessIdList = this.selectedAccessIdList.join(',')
        }
        if ((this.currentQueue.length !== 0 || this.currentdept.length !== 0) && this.selectedAgentListClone.length === 0) {
          query.selectedAgentList = '000000'
        }
        data.Query = Object.assign({}, data.Query, query)
        this.$store.dispatch('exportImAgentReport', data)
      },
      close (data) {
        if (data) {
          this.search()
        }
        this.isHeaderConfigShow = false
      },
      exportPdf () {
        this.dialogVisible = true
      },
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.webchat') + this.$t('report.imReportAgent') + searchTime(this.query), id: this.id})
      }
    },
    beforeMount () {
      if (isHasFunc('func_forbid_config_formula', this.$store.state.session.user)) {
        this.configFormula = false // 没有自定义公式的配置权限
      }
      let type = this.flag ? 'ecommerceAccessId' : 'accessIds'
      this.$store.dispatch('getCache', { type: type }).then(accessIds => {
        this.accessIdOptions = accessIds.map(accessId => ({ label: `${accessId.name}[${accessId.platform}]`, name: accessId.name, platform: accessId.platform, value: accessId._id }))
      })
      this.$store.dispatch('getDicCache', {type: 'mailQueues'}).then((res) => {
        if (res && res.success) {
          this.mailQueues = res.data
        }
      })
      this.$store.dispatch('getCache', {type: 'depts'}).then((dept) => {
        this.depts = dept.filter(item => {
          return item.pId
        })
        this.depts.push({
          name: '未分配部门',
          treePath: 'noDept'
        })
      })
      this.$store.dispatch('getCache', { type: 'agents' }).then(agents => {
        this.agentOptions = agents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id, deptId: agent.deptId ? agent.deptId : '' }))
        this.search()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .topTip
    color #459ae9
    padding 0px 18px 10px
  .agent
    .formal
      margin-left 10px
    .table
      padding-bottom: 20px
    .accs
      margin 14px 0 0px 0px
      .access
        margin-right 10px
      .el-select
        width 600px
    .agent_search
      .wrap_conti
        margin 14px 0 0 0px
        .chan_ag
          float left
          margin-right 16px
        .el-radio
          margin-right 30px
        .dept
          .el-radio
            margin-right 42px
    .skill
      margin-top 14px
      .ski
        margin-right 26px
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid $c-main
      text-align center
      line-height 15px
      border-radius 50%
      margin 0px 0 0 6px
      .iconfont
        border none
        font-size 10px
        color $c-main
    .agen
      margin 14px 0 0px 18px
      .el-select
        width 220px
    .search
      margin-bottom 34px
      .el-select
        width 400px
      .el-checkbox
        margin-left 16px
    .age
      display inline-block
      height 36px
      line-height 36px
      margin-right 16px
</style>
